<template>
	<view>

		<!-- 相机 -->
		<view class="cameraBox_con">
			<camera class="cameraCon" :device-position="device" :flash="flash" @error="error" >
				<cover-view class="watermarkCon" v-show="watermarkShow" @click="keepAdd">
					<cover-view class="watermarkProject">
						{{defaultWorksite.project_name}}
						<cover-view v-if="keepObj.selectType=='1'">[点工]</cover-view>
						<cover-view v-if="keepObj.selectType=='2'">[包工]</cover-view>
					</cover-view>
					<cover-view class="watermarkInfo">
						<cover-view class="watermarkLine"></cover-view>
						<cover-view class="watermarkList">
							<cover-view class="watermarkItem">时间：{{nowTime}}</cover-view>
							<cover-view class="watermarkItem">地点：{{address}}</cover-view>
							<cover-view v-if="keepObj.selectType=='1'">
								<cover-view class="watermarkItem">
									上班：{{keepObj.workNum}}
									<cover-view
										v-if="keepObj.workType=='1' || keepObj.workType=='2' || keepObj.workType=='4'">
										个工</cover-view>
									<cover-view v-if="keepObj.selectOver=='1'"></cover-view>
									<cover-view v-if="keepObj.selectOver=='2'">,加班：{{keepObj.overWork}}个工</cover-view>
									<cover-view v-if="keepObj.selectOver=='3'">,加班：{{keepObj.overWork}}个小时</cover-view>
								</cover-view>
								<!-- <cover-view class="watermarkItem">
									工资：{{keepObj.workMoney}}
								</cover-view> -->
							</cover-view>
							<cover-view class="watermarkItem" v-if="keepObj.selectType=='2'">
								工资：{{keepObj.workInput}}
							</cover-view>
							<!-- <cover-view class="watermarkItem">拍摄人：{{userInfo.name}}</cover-view> -->
						</cover-view>
					</cover-view>
					<cover-view class="watermarkSafe">
						<cover-image class="safeIcon" src="/static/camera/safeIcon.png">
						</cover-image>
						<cover-view class="safeText">记工本水印相机已验证时间地点真实性</cover-view>
					</cover-view>
				</cover-view>
				<!-- 切换相机正反面 -->
				<cover-image @click="deviceClick" class="deviceBtn" src="/static/camera/cameraIcon.png">
				</cover-image>
				<!-- 闪光灯开关 -->
				<cover-image @click="flashlightClick" class="flashlightBtn" :src="flashlightUrl"></cover-image>
				
				<cover-image @click="getMapKey" class="addressBtn" :src="dingweiUrl"></cover-image>
			</camera>
		</view>

		<!-- 底部 -->
		<view class="cameraPost_con">
			<view class="takeButton">
				<view class="takeBtn" @click="takeClick">拍照</view>
			</view>
		</view>

		<!-- 添加水印canvas -->
		<view class="canvasCon">
			<canvas canvas-id="firstCanvas"
				:style="'width:' + canvasWidth +'px;height:'+ canvasHeight + 'px;'"></canvas>
		</view>

		<!-- 添加记工组件 -->
		<AddKeep ref="keepCamera"></AddKeep>

		<!-- 选择工时组件 -->
		<WorkHour ref="workHour"></WorkHour>

	</view>
</template>

<script>
	import WorkHour from "@/components/keep/workHour.vue"
	import AddKeep from "@/components/camera/keepCamera.vue"

	export default {
		components: {
			AddKeep,
			WorkHour,
		},
		data() {
			return {
				// 默认工地信息
				defaultWorksite: JSON.parse(uni.getStorageSync('defaultWorksite')),

				// 水印开关
				watermarkShow: true,

				// camera组件参数
				device: 'back', // 前置或后置摄像头，值为front, back
				flash: 'off', // 闪光灯，值为auto, on, off

				// 水印信息
				nowTime: '', //日期
				address: '', //当前地址信息
				flashlightUrl: '/static/camera/flashlight_off.png',
				dingweiUrl: '/static/dingwei.png',
				// 水印canvas
				canvasWidth: 0,
				canvasHeight: 0,

				// 用户信息
				userInfo: {
					name: '',
				},

				/**
				 * 记工弹窗
				 */
				keepObj: {
					selectType: 1, // 默认点工
					workType: 1, // 默认1个工
					workNum: 1, // 提交的工
					workInput: '', // 输入的工
					workMoney: 0,
					selectOver: 1, // 加班
					overWork: 0,
					cameraUrl: '',
					cameraId: '',
					add_date: '',
					address: '',
					lng: '',
					lat: '',
				}
			}
		},
		created() {
			var _this = this;
			_this.getNowTime();
			_this.getMoney();
			_this.keepObj.add_date = _this.$util.nowDate();
			_this.keepObj.address = uni.getStorageSync('address');
			_this.keepObj.lng = uni.getStorageSync('longitude');
			_this.keepObj.lat = uni.getStorageSync('latitude');
		},
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad: function(options) {
			
		},
		onShow() {
			var _this = this;
			uni.$on('watermark', function(data) {
				console.log("==获取水印相机子组件的值==")
				console.log(data);
				_this.keepObj = data;
				// _this.getMoney();
				_this.getLocation();
				
			})
		},
		onReady() {
			// this.getMapKey();
			this.getLocation();
		},
		methods: {
			
			// 获取数据辞典信息
			getMapKey() {
				let _this = this;
				_this.$u.get('/api/plus.dictionaries/getDetail', {
					name: 'mapkey',
				}).then(res => {
					console.log("==获取数据辞典信息==");
					console.log(res);
					var mapKey = res.data.value;
					_this.getLocation(mapKey);
			
					// 缓存地图key
					uni.setStorageSync('mapKey', mapKey);
				}).catch(res => {
					console.log(res);
				})
			},
			
			// 获取当前位置
			getLocation() {
				
				
				var mapKey=uni.getStorageSync('mapKey');
				if(!mapKey){
					_this.mapKey()
				}
				let _this = this;
				wx.getLocation({
					type: 'wgs84',
					// geocode: true,
					success: function(res) {
						console.log('==获取当前位置的经纬度-成功1111111111==');
						console.log(res);
			
						_this.longitude = res.longitude;
						_this.latitude = res.latitude;
			
						// 设置经纬度缓存
						uni.setStorageSync('longitude', res.longitude);
						uni.setStorageSync('latitude', res.latitude);
			
						// 引入腾讯地图SDK核心类
						var QQMapWX = require('@/util/qqmap-wx-jssdk.min.js');
						var qqmapsdk = new QQMapWX({
							key: mapKey,
						});
						console.log('==22222==');
						// 根据经纬度获取所在位置
						qqmapsdk.reverseGeocoder({
							location: {
								longitude: res.longitude,
								latitude: res.latitude,
							},
							success: function(res) {
								console.log("==根据经纬度获取所在位置==");
								console.log(res);
								_this.address= res.result.formatted_addresses.rough;
								// 设置城市缓存
								uni.setStorageSync('province', res.result.ad_info.province);
								uni.setStorageSync('city', res.result.ad_info.city);
								uni.setStorageSync('area', res.result.ad_info.district);
								uni.setStorageSync('address', res.result.formatted_addresses.rough);
							},fail:function(res){
								console.log('=============')
								console.log(res)
							}
						});
					},
					fail: function(res) {
						console.log('res==========11=======')
						console.log(res)
						if(res.errMsg=='getLocation:fail auth deny'){
							uni.showModal({
								title:'授权提示',
								content:'您拒绝了定位授权，请重新打开',
								success(res){
									uni.openSetting({
										success(){
											_this.getLocation();
										}
									})
								}
							})
							return
						}
						uni.showToast({
							title:'频繁调用',
							'icon':'none'
						})
					}
				});
			},
			
			// 获取现在时间
			getNowTime: function() {
				var date = new Date(),
					year = date.getFullYear(),
					month = date.getMonth() + 1,
					day = date.getDate(),
					hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(),
					minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(),
					second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
				month >= 1 && month <= 9 ? (month = "0" + month) : "";
				day >= 0 && day <= 9 ? (day = "0" + day) : "";
				var timer = year + '年' + month + '月' + day + '日' + hour + ':' + minute + ':' + second;
				this.nowTime = timer;
				console.log('获取时间：', this.nowTime);
			},

			// 计算用户单日工资
			getMoney() {
				var _this = this;
				_this.$u.get('/api/project.work/getDayMoney', {
					num: _this.keepObj.workNum,
					overtime_type: _this.keepObj.selectOver, //加班类型：1无、2按工、3按小时
					overtime_num: _this.keepObj.overWork, //加班工时or小时数
				}).then(res => {
					uni.hideLoading();
					console.log("==计算用户单日工资==");
					console.log(res);
					_this.keepObj.workMoney = res.data;
					_this.$forceUpdate();
				}).catch(res => {
					console.log(res);
				})
			},

			// camera组件：用户不允许使用摄像头时触发
			error(e) {
				// console.log(e);
				uni.showModal({
					content: e.detail.errMsg,
					showCancel: false,
				})
				return;
			},

			// 切换相机正反面
			deviceClick() {
				if (this.device == 'front') {
					this.device = 'back'
				} else {
					this.device = 'front'
				}
			},

			// 闪光灯开关
			flashlightClick() {
				if (this.flash == 'off') {
					this.flash = 'on'
					this.flashlightUrl = '/static/camera/flashlight_on.png'
				} else {
					this.flash = 'off'
					this.flashlightUrl = '/static/camera/flashlight_off.png'
				}
			},

			// 点击拍照
			takeClick() {
				var _this = this;
				const cameraCtx = uni.createCameraContext();
				cameraCtx.takePhoto({
					quality: 'normal', //normal、high
					success: (res) => {
						console.log("==点击拍照==")
						console.log(res);
						var tempPath = res.tempImagePath;
						_this.addWatermark(tempPath);
					},
					fail: (res) => {
						wx.showToast({
							title: "相机拍照失败",
						})
					}
				});
			},

			// 调取相册
			// albumClick() {
			// 	var _this = this;
			// 	uni.chooseImage({
			// 		count: 1,
			// 		sizeType: ['original', 'compressed'],
			// 		sourceType: ['album'], //这要注意，camera调拍照，album是打开手机相册
			// 		success: (res) => {
			// 			console.log("==调取相册==")
			// 			console.log(res);
			// 			var tempPath = res.tempFilePaths[0];
			// 			_this.addWatermark(tempPath);
			// 		}
			// 	});
			// },

			// 添加canvas水印
			addWatermark(tempPath) {
				var _this = this;
				// 获取图片信息
				uni.getImageInfo({
					src: tempPath,
					success: (imgRes) => {
						console.log("==获取图片信息==")
						console.log(imgRes)
						let ctx = uni.createCanvasContext('firstCanvas');
						_this.canvasWidth = imgRes.width;
						_this.canvasHeight = imgRes.height;

						// 将图片src放到canvas内，宽高为图片大小
						ctx.drawImage(tempPath, 0, 0, imgRes.width, imgRes.height)

						// 绘制工地背景
						ctx.strokeStyle = 'rgba(50,127,232,0.8)'
						ctx.strokeRect(20, imgRes.height - 300, 560, 60)
						ctx.fillStyle = 'rgba(50,127,232,1)'
						ctx.fillRect(20, imgRes.height - 300, 560, 60)

						// 绘制黄色矩形
						ctx.strokeStyle = '#FF8A00'
						ctx.strokeRect(20, imgRes.height - 220, 6, 160)
						ctx.fillStyle = '#FF8A00'
						ctx.fillRect(20, imgRes.height - 220, 6, 160)

						ctx.setFontSize(24) //注意：设置文字大小必须放在填充文字之前，否则不生效
						ctx.setFillStyle('#fff')

						// 点工
						if (_this.keepObj.selectType == '1') {
							ctx.fillText(_this.defaultWorksite.project_name + '：' + '[点工]', 40, imgRes
								.height -
								260)
						}
						// 包工
						if (_this.keepObj.selectType == '2') {
							ctx.fillText(_this.defaultWorksite.project_name + '：' + '[包工]', 40, imgRes
								.height -
								260)
						}

						ctx.fillText('时间：' + _this.nowTime, 40, imgRes.height - 190)
						ctx.fillText('地点：' + _this.address, 40, imgRes.height - 150)

						// 点工
						if (_this.keepObj.selectType == '1') {
							// workType：1 工、2 0.5工、3休息、4自定义工
							if (_this.keepObj.workType == '1' || _this.keepObj.workType == '2' || _this.keepObj
								.workType == '4') {
								ctx.fillText('上班:' + _this.keepObj.workNum + '个工', 40, imgRes.height - 110)
							}
							if (_this.keepObj.workType == '3') {
								ctx.fillText('上班:' + _this.keepObj.workNum, 40, imgRes.height - 110)
							}
							if (_this.keepObj.selectOver == '2') {
								ctx.fillText('上班:' + _this.keepObj.workNum + '个工,加班' + _this.keepObj.overWork +
									'个工', 40,
									imgRes.height - 110)
							}
							if (_this.keepObj.selectOver == '3') {
								ctx.fillText('上班:' + _this.keepObj.workNum + '个工,加班' + _this.keepObj.overWork +
									'个小时',
									40, imgRes.height - 110)
							}
							// ctx.fillText('工资：' + _this.keepObj.workMoney, 40, imgRes.height - 70)
						}

						// 包工
						if (_this.keepObj.selectType == '2') {
							ctx.fillText('工资:' + _this.keepObj.workInput, 40, imgRes.height - 110)
						}

						// 安全提示
						ctx.drawImage('/static/camera/safeIcon.png', 20, imgRes.height - 45, 30, 30)
						ctx.fillText('记工本水印相机已验证时间地点真实性', 60, imgRes.height - 20)

						ctx.draw(false, function() {
							uni.showLoading({
								title: '图片保证中'
							});
							setTimeout(function(){
								uni.canvasToTempFilePath({
									canvasId: 'firstCanvas',
									fileType: 'jpg',
									quality: 1,
									success: (res) => {
										// console.log(res);
										var filePath = res.tempFilePath;
										//_this.filePath = filePath;
								
										// 保存到相册
										uni.saveImageToPhotosAlbum({
											filePath: filePath,
											success(res) {
												uni.showToast({
													title: '已保存到相册',
													duration: 2000
												});
												uni.hideLoading()
											}
										});
								
										_this.imageUpload(filePath);
									},
									fail: (res) => {
										console.log(res)
									}
								})
							},1000)
							
						})
					}
				})
			},

			// 图片预览
			imageUpload(filePath) {
				var _this = this;
				var keepJson = '';
				uni.navigateTo({
					url: './watermarkPreview?keepJson=' + keepJson + '&filePath=' + filePath
				})
			},

			// 添加记工
			keepAdd() {
				var _this = this;
				_this.$refs.keepCamera.clearData();
				_this.$refs.keepCamera.addShow = true;
			},

		},
	}
</script>

<style>
	page {
		background-color: #fff;
	}
</style>
<style lang="scss" scoped>
	// 相机
	.cameraBox_con {
		width: 100%;
		height: 100vh;
	}

	.cameraCon {
		width: 100%;
		height: 55vh;
	}

	.watermarkCon {
		width: 560rpx;
		padding: 0 20rpx;
		color: #fff;
		font-size: 28rpx;
		box-sizing: border-box;
		overflow: hidden;
		position: absolute;
		bottom: 0;
		left: 0;
	}

	.watermarkProject {
		width: 100%;
		height: 60rpx;
		line-height: 60rpx;
		padding: 0 20rpx;
		background-color: rgba(50, 127, 232, 0.8);
		box-sizing: border-box;
		overflow: hidden;
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.watermarkInfo {
		overflow: hidden;
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.watermarkLine {
		width: 6rpx;
		height: 208rpx;
		background-color: #FF8A00;
		overflow: hidden;
	}

	.watermarkList {
		flex: 2;
		margin-left: 20rpx;
	}

	.watermarkItem {
		width: 100%;
		padding: 10rpx 0;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		display: flex;
		align-items: center;
	}

	.watermarkSafe {
		width: 100%;
		overflow: hidden;
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.safeIcon {
		width: 30rpx;
		height: 30rpx;
	}

	.safeText {
		margin-left: 10rpx;
	}

	// 切换镜头
	.deviceBtn {
		width: 52rpx;
		height: auto;
		position: absolute;
		right: 44rpx;
		bottom: 580rpx;
	}

	// 闪光灯开关
	.flashlightBtn {
		width: 40rpx;
		height: auto;
		position: absolute;
		right: 50rpx;
		bottom: 450rpx;
	}
	
	.addressBtn{
		width: 60rpx;
		height: auto;
		position: absolute;
		right: 50rpx;
		bottom: 50rpx;
	}

	// 底部
	.cameraPost_con {
		width: 100%;
		height: 45vh;
		padding: 0 30rpx;
		box-sizing: border-box;
		overflow: hidden;
		position: absolute;
		bottom: 0;
		left: 0;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.takeButton {
		width: 160rpx;
		height: 160rpx;
		line-height: 160rpx;
		padding: 8rpx;
		border: 10rpx #327FE8 solid;
		border-radius: 50%;
		overflow: hidden;
	}

	.takeBtn {
		width: 100%;
		height: 100%;
		border-radius: 50%;
		color: #fff;
		background-color: #007AFF;
		overflow: hidden;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	// 添加水印canvas
	.canvasCon {
		width: 0;
		height: 0;
		position: fixed;
		left: 900000px;
		z-index: -999;
		overflow: hidden;
	}
</style>
